﻿using KAsFrame.Common.Dto;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using System.Linq;
using KAsFrame.Common.Extensions;
using System;
using Microsoft.AspNetCore.Authorization;
using System.IO;
using KAsFrame.Common.Const;
using SqlSugar;
using KAsFrame.Common.Attr;
using Microsoft.Extensions.Configuration;

namespace KAsFrame.Common.Controllers
{
    [Route(ConstConfig.ApiRouteConfig)]
    [ApiController]
    public class ToolController : ControllerBase
    {
        private readonly ISqlSugarClient _db;
        private readonly IConfiguration _config;

        public ToolController(ISqlSugarClient db, IConfiguration configuration)
        {
            _db = db;
            _config = configuration;
        }

        [HttpGet]
        public ApiResult<List<EnumDto>> GetEnums(string key)
        {
            if (key.IsNullOrWhiteSpace())
                return ApiResult<List<EnumDto>>.IsError("请传入正确的key值");

            // 获取运行目录下所有程序集
            var path = AppDomain.CurrentDomain.BaseDirectory;
            string[] dllFiles = Directory.GetFiles(path, "*.dll", SearchOption.TopDirectoryOnly);

            Type enumType;
            // 遍历程序集找到对应的Enum，对应枚举类必须用特性ReadEnumAttribute标记，否则无法找到
            foreach (var item in dllFiles)
            {
                var assembly = Assembly.LoadFrom(item);
                enumType = assembly.GetTypes().FirstOrDefault(x => x.IsEnum && x.Name.StartsWith(key)
                    && x.GetCustomAttribute<ReadEnumAttribute>() != null);
                if (enumType != null)
                {
                    var result = new List<EnumDto>();
                    foreach (var enumItem in Enum.GetValues(enumType))
                    {
                        result.Add(new EnumDto()
                        {
                            Key = enumType.Name,
                            EnumCode = Convert.ToInt32(enumItem),
                            EnumName = enumItem.ToString(),
                            EnumDesc = (enumItem as Enum).GetDescription()
                        });
                    }
                    return ApiResult<List<EnumDto>>.IsSuccess(data: result);
                }
            }

            return ApiResult<List<EnumDto>>.IsError("请传入正确的key值");
        }

        [HttpPost]
        [AllowAnonymous]
        public ApiResult<int> InitDataBase([FromBody] string pwd)
        {
            try
            {
                if (pwd == _config["InitDbPwd"])
                {
                    // 若数据库不存在，创建数据库
                    _db.DbMaintenance.CreateDatabase();
                    // 创建或更新数据结构
                    var entityTypes = new List<Type>();
                    var path = AppDomain.CurrentDomain.BaseDirectory;
                    string[] dllFiles = Directory.GetFiles(path, "*.dll", SearchOption.TopDirectoryOnly);
                    foreach (var item in dllFiles)
                    {
                        var assembly = Assembly.LoadFrom(item);
                        var tempTypes = assembly.GetTypes()
                            .Where(x => x.IsClass && x.IsPublic && x.GetCustomAttribute<SugarTable>() != null)
                            .ToList();
                        if (tempTypes.IsAny())
                            entityTypes.AddRange(tempTypes);
                    }
                    _db.CodeFirst.SetStringDefaultLength(64).InitTables(entityTypes.ToArray());
                    // 插入配置数据
                    // 判断配置数据是否存在，插入或更新等
                    // ......
                    return ApiResult<int>.IsSuccess();
                }
                else
                {
                    return ApiResult<int>.IsError();
                }
            }
            catch (Exception ex)
            {
                return ApiResult<int>.IsError(ex.Message);
            }
        }
    }
}
